/*
 * Created on Mar 8, 2010
 */
package com.mgmaps.app;

import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import com.mgmaps.utils.ExtLogger;
import com.mgmaps.utils.LS;

public abstract class APPMidlet extends MIDlet {
  
  public static APPMidlet instance;
  private APPCanvas canvas;
  
  /**
   * Constructor for APPMidlet.
   */
  public APPMidlet() {
    instance = this;
  }
  
  /**
   * Get the value of an app property.
   * @param propKey property key
   * @param defaultValue default value
   * @return the value of the property
   */
  protected String getAppProp(String propKey, String defaultValue) {
    String result = getAppProperty(propKey);
    return (result == null) ? defaultValue : result.trim();
  }
  
  protected abstract void saveSettings();
  protected abstract void initializeSettings();
  protected abstract void loadSettings();
  protected abstract APPCanvas createCanvas();
  
  public void destroyApp(boolean arg0) throws MIDletStateChangeException {
    if (APPSettings.featureBacklight && APPSettings.platformHandler != null)
      APPSettings.platformHandler.backlightOff();
    
    // Settings.save calls savePoint
    // Settings.save();
    saveSettings();
    
    if (APPSettings.featureMap && canvas != null && canvas.getMap() != null)
      canvas.getMap().stopMapping();
    
    APPSettings.notifyExit();
    canvas.notifyExit();
    canvas = null;
    instance = null;
    notifyDestroyed();
  }

  protected void pauseApp() {
    notifyPaused();
  }

  protected void startApp() throws MIDletStateChangeException {
    if (canvas == null) {
      ExtLogger.initializeLog();
      try {
        initializeSettings();
        APPSettings.version = getAppProp("MIDlet-Version", APPSettings.version);
        APPSettings.identify(); // Generate or use a phoneGUID
        loadSettings();
        LS.setLanguage(APPSettings.language);
        canvas = createCanvas();
      }
      catch (Exception ex) {
        ExtLogger.handle(ex, true, "Exception while initializing application");
        return;
      }
    }

    canvas.setCanvas();
    
    // backlight (thread/timer)
    if (APPSettings.featureBacklight && APPSettings.backlightOn && APPSettings.platformHandler != null)
      APPSettings.platformHandler.backlightOn();
  }
}
